import axios from "axios";
import { getToken, clearToken } from "./token";
import router from "../router";

const http = axios.create({
  baseURL: "http://geek.itheima.net/v1_0",
  timeout: 5000,
});

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  (e) => Promise.reject(e)
);

// axios响应式拦截器
http.interceptors.response.use(
  (res) => res.data,
  (e) => {
    console.log(e);
    // 401 -- token失效
    if(e.response.status === 401){
      clearToken()
      // router实例
      router.navigate('/login')
    }
    return Promise.reject(e);
  }
);

export default http;
